﻿using Newtonsoft.Json.Linq;
using System.Diagnostics;

namespace ttwin_cli
{
    internal class Program
    {
        static string arg_hostpath = ".";
        static bool arg_isdebug = false;
        static string arg_indexfile = "index.html";
        static string arg_toweb = "";
        static bool InitArgs(string[] args)
        {
            string hostpath = null;
            bool? isdebug = null;
            string indexfile = null;
            try
            {
                foreach (var arg in args)
                {
                    if (arg[0] == '-')
                    {
                        if (arg.IndexOf("-index=") >= 0)
                        {
                            if (indexfile != null)
                            {
                                throw new Exception("repeat arg -index");
                            }
                            indexfile = arg.Substring(7);
                        }
                        else if (arg == "-debug")
                        {
                            if (isdebug != null)
                                throw new Exception("repeat arg -debug");
                            isdebug = true;
                        }
                        else if (arg.IndexOf("-args=") >= 0)
                        {
                            arg_toweb = arg.Substring(6);
                        }
                    }
                    else
                    {
                        if (hostpath != null)
                        {
                            throw new Exception("repeat arg hostpath");
                        }
                        hostpath = arg;
                    }
                }
                if (hostpath == null)
                    return false;
                arg_hostpath = System.IO.Path.GetFullPath(hostpath);
                if (isdebug != null)
                {
                    arg_isdebug = isdebug.Value;
                }
                if (indexfile != null)
                {
                    arg_indexfile = indexfile;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Err Arg:" + e.ToString());
            }
            return true;
        }
        static void Main(string[] args)
        {
            var b = InitArgs(args);
            if (!b)
            {
                Console.WriteLine("Use : ttwin_cli HostPath [-debug] [-index=IndexFileName] [-argv=]");
                Console.WriteLine("HostPath most of time maybe you want = .");
                Console.WriteLine("-debug default = false");
                Console.WriteLine("-index default = index.html");
                Console.WriteLine("-argv will tran to open web with get method");
                return;
            }
            Console.WriteLine("HostPath =" + arg_hostpath);
            Console.WriteLine("-debug default =" + arg_isdebug);
            Console.WriteLine("-index default =" + arg_indexfile);
            InitAsync();
            while (true)
            {
                //Console.Write(">");
                var line = Console.ReadLine();
                if (line == "exit")
                    break;
            }
            LocalExt.Logger.OnLog("LocalExt exit.");
        }

        static void InitAsync()
        {
            //static string arg_hostpath = ".";
            //static bool arg_isdebug = false;
            //static string arg_indexfile = "index.html";


            //var json = JObject.Parse(System.IO.File.ReadAllText("index.json"));
            //if (json.ContainsKey("debug"))
            {
                //var debugstr = json["debug"].ToString().ToLower();
                //var debug = debugstr == "true" || debugstr == "1";
                LocalExt.Debug = arg_isdebug;
            }
            //string hostdir = ".";
            //if (json.ContainsKey("hostdir"))
            //{
            //    hostdir = json["hostdir"].ToString();
            //}
            //hostdir = System.IO.Path.GetFullPath(hostdir);




            int localport = 8848;
            bool httpsucc = false;
            for (var i = 0; i < 10; i++)
            {
                try
                {
                    LocalExt.Start(localport, arg_hostpath);
                    httpsucc = true;
                    break;
                }
                catch (Exception err)
                {
                    localport++;
                }
            }
            if (!httpsucc)
            {
                LocalExt.Logger.OnLog("扩展服务起不来");
                return;
            }


            LocalExt.Logger.OnLog("localext at:" + localport);
            LocalExt.extInfo = "local ext 001";
            LocalExt.OnSet_Debug += (endebug) =>
            {
                LocalExt.Logger.OnLog("recv from frontend:OnSet_Debug=" + endebug + " 但是控制台没有Debug面板可以显示。");
            };






            //var file =json["startpage"].ToString();
            
            var url = new Uri("http://localhost:" + localport + "/html/" + arg_indexfile + "?_localext_=" + localport + "&args=" + arg_toweb);
            LocalExt.Logger.OnLog("file server at:" + url.ToString());

            LocalExt.OpenUrl(url);
            LocalExt.Logger.OnWarn("不要关闭此窗口");
            LocalExt.Logger.OnWarn("do not close this win");
        }
    }
}